<script setup lang="tsx">
defineOptions({
  name: "bottleInfo"
});

import { ref, h, onMounted, onUnmounted, markRaw, getCurrentInstance, provide } from "vue";
import { queryGasBottleInfoList, importGasBottleInfoData, deleteGasBottleInfo } from "@/api/modules/operation";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import { PxIcon } from "px-ui";
import { Edit, Delete, Download } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import addBottleInfo from "./addBottleInfo.vue";
import batchUploadMSDS from "./batchUploadMSDS.vue";
import importBottle from "./importBottle.vue";
import { useMessageBox } from "@/hooks/useCommon";
import checkLogs from "@/views/gas/components/checkLogs.vue";

interface Props {
  //  1 在供气瓶  2 返库气瓶  3 过期气瓶
  type: 1 | 2 | 3;
}

const props = withDefaults(defineProps<Props>(), { type: 1 });

provide("bottleType", props.type);

const gap = 88;
const defaultHeight = 606;
const objectModelTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
const searchOption = ref<Array<CommonSearch.SearchOption>>([
  {
    label: "料号",
    key: "materialNo",
    value: "",
    type: "input",
    placeholder: "请输入料号",
    span: 5
  },
  {
    label: "气体名称",
    key: "gasName",
    value: "",
    type: "input",
    placeholder: "请输入气体名称",
    span: 5
  }
]);
const tableCloumns = ref<Array<CommonTable.TableCloumnsType>>([
  {
    label: "料号",
    prop: "materialNo",
    sortable: true,
    width: 180
  },
  {
    label: "气体名称",
    prop: "gasName",
    width: 180
  },
  {
    label: "描述",
    prop: "description",
    width: 180
  },
  {
    label: "MSDS",
    prop: "fileDTOList",
    width: 200,
    render({ row }: any, ins) {
      const { fileDTOList = [] } = row;
      if (!fileDTOList?.length) return () => "--";
      const { id = "", fileName = "", moduleName = "", originalName = "" } = fileDTOList[0];
      const flag = ref<boolean>(false);
      const onMouseOverHandler = () => {
        flag.value = true;
      };
      const onMouseLeaveHandler = () => {
        flag.value = false;
      };
      const downloadFn = () => {
        const params = { id, fileName, moduleName };
        const { proxy }: any = ins;
        proxy.download("post", "/sharing/api/v1/file/download", params, row.fileName);
      };
      return () =>
        h(
          <div
            style={{
              width: "100%",
              display: "flex",
              alignItems: "center",
              gap: "2px",
              color: flag.value ? "var(--px-color-primary-light-3)" : "var(--px-color-primary)",
              cursor: "pointer"
            }}
            onMouseOver={onMouseOverHandler}
            onMouseLeave={onMouseLeaveHandler}
            onClick={downloadFn}
          >
            <span style={{ flex: 1, width: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {originalName || fileName || "--"}
            </span>
            <PxIcon size={18}>
              <Download />
            </PxIcon>
          </div>
        );
    }
  }
]);
const params = ref<any>({});
// 弹框类型 add 新增   edit 编辑
const addType = ref<"add" | "edit">("add");
const bottleId = ref<string>("");
const addDialogTableVisible = ref<boolean>(false);
const batchUploadMSDSVisible = ref<boolean>(false);
const checkLogsDialogVisible = ref<boolean>(false);
const importBottleVisible = ref<boolean>(false);
const ids = ref<Array<any>>([]);

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "编辑",
    auth: "GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_EDITBTN",
    icon: markRaw(Edit),
    click: (scope: any) => edit(scope)
  },
  {
    content: "删除",
    auth: "GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_DELETEBTN",
    icon: markRaw(Delete),
    type: "danger",
    click: (scope: any) => del(scope)
  }
];

let currentParams: any = {};

const getRowKey = row => {
  return row.id;
};

const sortChangeHandler = ({ column, order }: CommonTable.SortParams) => {
  const { property: orderBy = "" } = column;
  // ascending  descending
  const isAsc = order === "ascending" ? true : order === "descending" ? false : true;
  currentParams["orderBy"] = orderBy;
  currentParams["isAsc"] = isAsc;
  if (!order) {
    currentParams.orderBy && delete currentParams.orderBy;
    currentParams.isAsc && delete currentParams.isAsc;
  }
  updateParams();
};

const selectionChangeHandler = (val: Array<any>) => {
  ids.value = [];
  if (val?.length) {
    ids.value = val.map(item => item.id);
  }
};

const updateParams = () => {
  params.value = { ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const resetSearchFormHandler = () => {
  currentParams = {};
  updateParams();
};

const addFn = () => {
  bottleId.value = "";
  addType.value = "add";
  addDialogTableVisible.value = true;
};

const { proxy }: any = getCurrentInstance();

const downloadFn = useThrottleFn(async () => {
  const url = "/operation/api/v1/gas/gasMaterialMapping/downloadTemplate";
  proxy.download("post", url);
}, delay);

const batchImportFn = () => {
  importBottleVisible.value = true;
};

const batchExportFn = useThrottleFn(async () => {
  const url = "/operation/api/v1/gas/gasMaterialMapping/exportData";
  const params = commonTableRef.value.getParams();
  proxy.download("post", url, params);
  PxMessageBox.alert("正在导出您筛选的数据，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "批量导出", {
    confirmButtonText: "我知道了"
  });
}, delay);

const batchUploadMSDSFn = () => {
  if (ids.value?.length) {
    batchUploadMSDSVisible.value = true;
  } else {
    PxMessage.error("请选择料号！！");
  }
};

const edit = scope => {
  const {
    row: { id = "" }
  } = scope;
  bottleId.value = id;
  addType.value = "edit";
  addDialogTableVisible.value = true;
};

const del = async scope => {
  const {
    row: { materialNo: labelName = "", id = "" }
  } = scope;
  const msg = `确定要删除气瓶 ${labelName}吗？`;
  useMessageBox("delete", msg, async () => {
    const params = { labelName, id };
    await deleteGasBottleInfo(params);
    PxMessage.success("删除成功！");
    commonTableRef.value.queryTableData();
  });
};

const checkLogsFn = () => {
  checkLogsDialogVisible.value = true;
};

const submitHandler = (flag: boolean = false) => {
  const message = flag ? "导入成功" : addType.value === "add" ? "创建成功" : "编辑成功";
  PxMessage.success(message);
  commonTableRef.value.queryTableData(null, true);
};

const submitHandler2 = () => {
  const message = "上传成功";
  PxMessage.success(message);
  commonTableRef.value.clearSelection();
  commonTableRef.value.queryTableData(null, true);
};

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div class="all-orders">
    <div class="all-orders-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        :row-num="4"
        :operation-span="3"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="resetSearchFormHandler"
      />
    </div>
    <div class="all-orders-btns">
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_ADDBTN'" type="primary" @click="addFn">新增</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_DOWNLOADBTN'" type="primary" plain @click="downloadFn">模板下载</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_IMPORTBTN'" type="primary" plain @click="batchImportFn">批量导入</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_EXPORTBTN'" type="primary" plain @click="batchExportFn">批量导出</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_UPLOADMSDSBTN'" type="primary" plain @click="batchUploadMSDSFn"
        >批量上传MSDS</px-button
      >
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_CHECKLOGS_BTN'" type="primary" plain @click="checkLogsFn">查看日志</px-button>
    </div>
    <div ref="objectModelTableRef" class="all-orders-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        selection
        :operationOptions="operationOptions"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :row-key="getRowKey"
        :axiosApi="queryGasBottleInfoList"
        :params="params"
        @sort-change="sortChangeHandler"
        @selection-change="selectionChangeHandler"
      />
    </div>
    <addBottleInfo v-if="addDialogTableVisible" :id="bottleId" v-model="addDialogTableVisible" :type="addType" @submit="submitHandler" />
    <batchUploadMSDS v-if="batchUploadMSDSVisible" v-model="batchUploadMSDSVisible" :ids="ids" @submit="submitHandler2" />
    <importBottle
      v-if="importBottleVisible"
      v-model="importBottleVisible"
      :uploadApi="importGasBottleInfoData"
      :lifeCycle="type"
      @submit="submitHandler(true)"
    />
    <checkLogs v-if="checkLogsDialogVisible" v-model="checkLogsDialogVisible" type="料号与气体映射" title="气瓶信息" />
  </div>
</template>

<style lang="scss" scoped>
.all-orders {
  width: 100%;
  background-color: #fff;

  .all-orders-search {
    width: 100%;
  }

  .all-orders-btns {
    display: flex;
    align-items: center;
    margin-top: 16px;
  }

  .all-orders-table {
    margin-top: 16px;
  }
}
</style>
